<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Service\Wechat;

class JSSDK
{

    private $appId = '';

    private $appSecret = '';

    public static $instance = null;

    static public function getInstance()
    {
        return self::$instance ? self::$instance : (self::$instance = new self());
    }

    public function import($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;

        $res = "<script src='http://res.wx.qq.com/open/js/jweixin-1.2.0.js'></script>";
        $signPackage = $this->getSignPackage($appId, $appSecret);
        return $res . "<script>wx.config(" . json_encode($signPackage) . ")</script>";
    }

    public function getSignPackage($appId, $appSecret, $url = '')
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $jsapiTicket = $this->getJsApiTicket();
        empty($url) == true && $url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            'debug' => defined('DEBUG_WECHAT_JSSDK') && DEBUG_WECHAT_JSSDK,
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
//            "rawString" => $string,
            "jsApiList" => array(
                'onMenuShareAppMessage',
                'onMenuShareTimeline',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone',
                'scanQRCode',
                'getLocation',
                'chooseImage',
                'previewImage',
                'uploadImage'
            )
        );

        return $signPackage;
    }

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket()
    {
        $cache_key = "wechat_jsapi_ticket" . $this->appId;
        $ticket = S($cache_key);
        if (!$ticket) {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($response = OE('util')->curl($url));
            $ticket = $res->ticket;
            if ($ticket) {
                S($cache_key, $ticket, 7000);
            } else {
                throw new \Exception($response);
            }
        }
        return $ticket;
    }

    //强制更新 JsApiTicket
    public function updateJsApiTicket($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $cache_key = "wechat_jsapi_ticket" . $this->appId;
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $res = json_decode($response = OE('util')->curl($url));
        $ticket = $res->ticket;
        if ($ticket) {
            S($cache_key, $ticket, 7000);
        } else {
            throw new \Exception($response);
        }

        return true;
    }

    private function getAccessToken()
    {
        $data = json_decode(S('token'));
        if ($data->expire_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($response = OE('util')->curl($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                S('token', json_encode($data), 7000);
            } else {
                throw new \Exception($response);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }
}